import 'package:flutter/material.dart';

class AutoCompleteDemo extends StatefulWidget {
  const AutoCompleteDemo({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _AutoCompleteDemoState createState() => _AutoCompleteDemoState();
}

class _AutoCompleteDemoState extends State<AutoCompleteDemo> {
  final List<Country> countries = [
    Country(id: 1, name: '中国'),
    Country(id: 2, name: '美国'),
    Country(id: 3, name: '印度'),
    Country(id: 4, name: '俄罗斯'),
    Country(id: 5, name: '英国'),
    Country(id: 6, name: '巴西'),
    Country(id: 7, name: '法国'),
    Country(id: 8, name: '德国'),
  ];

  var selectedCountry = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AutoComplete Demo'),
      ),
      body: Center(
        child: Autocomplete<Country>(
          optionsBuilder: (TextEditingValue textEditingValue) {
            return Future.delayed(const Duration(milliseconds: 2000), () {
              return countries
                  .where(
                      (country) => country.name.contains(textEditingValue.text))
                  .toList();
            });
          },
          onSelected: (Country country) {
            selectedCountry = country.name;
          },
          fieldViewBuilder: (BuildContext context,
              TextEditingController textEditingController,
              FocusNode focusNode,
              VoidCallback onFieldSubmitted) {
            return TextField(
              controller: textEditingController,
              focusNode: focusNode,
              onChanged: (text) {
                selectedCountry = text;
              },
              decoration: const InputDecoration(
                labelText: '国家',
              ),
            );
          },
          displayStringForOption: (Country country) =>
              '[${country.id}] ${country.name}',
          initialValue: TextEditingValue(text: selectedCountry),
        ),
      ),
    );
  }
}

class Country {
  final int id;
  final String name;

  Country({required this.id, required this.name});
}
